package com.rongxue.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.BankBusinessService;
import com.rongxue.service.CashInAndOutService;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Service
@Transactional
public class BankBusinessServiceImpl implements BankBusinessService {

    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SBankTypeMapper bankTypeMapper;
    @Autowired
    private SBankTypeMapper SBankTypeMapper;

    @Autowired
    private SMobileCodeMapper sMobileCodeMapper;

    @Autowired
    private SUserRedenvelopeMapper sUserRedenvelopeMapper;


    private static final Logger logger = LoggerFactory.getLogger(BankBusinessServiceImpl.class);

    //银行卡类别验证key
    private static final String BANKCARD_INFO_KEY = "716766eb5ab0ea12928c1836ed8204a4";

    //银行卡四要素
    private static final String BANKCARD_4_KEY = "d4a95bb091230308f9fd6738369d324a";

    //银行卡类别验证请求url
    private static final String BANKCARD_INFO_URL = "http://v.juhe.cn/bankcardinfo/query";

    //银行卡四要素请求url
    private static final String BANKCARD_4_URL = "http://v.juhe.cn/verifybankcard4/query";

    @Override
    public ObjectResult bindingBankNo(XMLBean xmlBean) {

//        //验证码校验
//        MobileCode  mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
//        if(!mobileCode.getCode().equals(xmlBean.getMobile_auth_code())){
//            return ObjectResult.build("0","验证码错误");
//        }
//        if(System.currentTimeMillis()-mobileCode.getSend_time()>5*60*1000){
//            return ObjectResult.build("0","验证码失效");
//        }

        //绑卡
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        if (resultUser == null){
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        if (resultUser.getCardNoAuth() == 1){
            return ObjectResult.build("0", "您已绑定身份证");
        }

        //查询身份证是否被绑定
        SUser user = this.userMapper.selectUserIdByIdAndCardNo(xmlBean.getCard_no());
        if (user != null) {
            return ObjectResult.build("0", "该身份证已被绑定");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank != null){
            return ObjectResult.build("0", "您已绑定银行卡");
        }

        HashMap<String, String> bankCardInfoMap = new HashMap<>();
        bankCardInfoMap.put("bankcard", xmlBean.getBank_no());
        bankCardInfoMap.put("key", BANKCARD_INFO_KEY);
        //验证卡类型
        ObjectResult result = HttpClientUtil.verificationOfBankCard(BANKCARD_INFO_URL, bankCardInfoMap);

        if (result.getCode().equals("1")){

            Map<String,Object> resultMap = (Map<String, Object>) result.getData();
            Map<String,Object> result_1 = (Map<String, Object>) resultMap.get("result");

            if ((int)resultMap.get("error_code") != 0){

                return ObjectResult.build("0", resultMap.get("reason").toString());

            } else if ((int)resultMap.get("error_code") == 10012){

                ExceptionUtils.recordException(true,"聚合银行卡类型及真伪查询,可请求的次数不足","", null);
                return ObjectResult.build("0", "身份信息审核中,请稍后重试");


            }else if ((int)resultMap.get("error_code") == 10020){

                return ObjectResult.build("0", "接口维护,请稍后重试");

            } else if (result_1.get("bankcard").equals(xmlBean.getBank_no())){


                if (!result_1.get("cardtype").equals("借记卡")){

                    return ObjectResult.build("0", "不支持"+result_1.get("cardtype"));
                }

                //支持的银行查询,并获取机构号
                SBankType sBankType = SBankTypeMapper.selectByBankFullName("%"+result_1.get("bank")+"%");
                if (sBankType == null || sBankType.getBankFullName() == null || sBankType.getBankFullName().equals("")){
                    return ObjectResult.build("0", "不支持此卡");
                }

                //四要素验证
                String serialNumber = new P2PMessageUtils().getRechargeNo("V") + RandomUtil.getRandom(8);
                HashMap<String, String> bankCard4Map = new HashMap<>();
                bankCard4Map.put("key", BANKCARD_4_KEY);
                bankCard4Map.put("realname", xmlBean.getReal_name());
                bankCard4Map.put("idcard", xmlBean.getCard_no());
                bankCard4Map.put("bankcard", xmlBean.getBank_no());
                bankCard4Map.put("mobile", xmlBean.getMobile());
//                bankCard4Map.put("uorderid", serialNumber);

                ObjectResult objectResult = HttpClientUtil.verificationOfBankCard(BANKCARD_4_URL, bankCard4Map);

                if (objectResult.getCode().equals("1")){

                    Map<String,Object> dataMap = (Map<String, Object>) objectResult.getData();
                    Map<String,Object> dataMap_1 = (Map<String, Object>) dataMap.get("result");

                    if ((int)resultMap.get("error_code") != 0){

                        return ObjectResult.build("0", resultMap.get("reason").toString());

                    } else if ((int)resultMap.get("error_code") == 10012){

                        ExceptionUtils.recordException(true,"聚合银行卡类型及真伪查询,可请求的次数不足","", null);
                        return ObjectResult.build("0", "身份信息审核中,请稍后重试");


                    }else if ((int)resultMap.get("error_code") == 10020){

                        return ObjectResult.build("0", "接口维护,请稍后重试");

                    }else if (dataMap_1.get("res").toString().equals("1")){

                        if (dataMap_1.get("realname").equals(xmlBean.getReal_name()) && dataMap_1.get("bankcard").equals(xmlBean.getBank_no())
                                && dataMap_1.get("idcard").equals(xmlBean.getCard_no()) && dataMap_1.get("mobile").equals(xmlBean.getMobile())){


                            try {
                                //更新数据库,用户
                                resultUser.setRealNameAuth(1);
                                resultUser.setCardNoAuth(1);
                                resultUser.setCardNo(xmlBean.getCard_no());
                                resultUser.setRealName(xmlBean.getReal_name());
                                resultUser.setCardType(1);
                                userMapper.updateByPrimaryKeySelective(resultUser);

                                Long user_Id = resultUser.getId();
                                //更新数据库,银行卡
                                SUserBank bank = new SUserBank();
                                bank.setUserId(user_Id);//用户id
                                bank.setBankName(result_1.get("bank").toString());//发卡银行名称
                                bank.setPayType("10");//默认是快捷支付（借记卡）
                                bank.setBankCode(sBankType.getBank_code());//银行编号
                                bank.setIdType(1);//身份证或者是其他
                                bank.setMobile(xmlBean.getMobile());//卡的手机号
                                bank.setIdNo(xmlBean.getCard_no());//身份证号
                                bank.setAcctName(xmlBean.getReal_name());//该卡归属人姓名
                                bank.setPayChannel(Integer.valueOf(1));//支付渠道---连连支付
                                bank.setIsDeleted(Integer.valueOf(0));//默认是解绑状态等 银行绑定成功该变该值
                                bank.setBankCardNo(xmlBean.getBank_no());//银行卡号
                                bank.setHasPaySuccess(Integer.valueOf(1));//是否成功支付过---1未支付成功,2支付成功
                                bank.setAddTime(new Date());//添加日期
                                bank.setAddUserId(user_Id);//添加人
                                bank.setModifyTime(new Date());
                                bank.setModifyUserId(user_Id);
                                userBankMapper.insertSelective(bank);


                                //实名认证红包
//                                String[][] array={{"28","5000","30","30"},{"66","10000","30","30"}
//                                        ,{"88","30000","30","30"},{"150","50000","30","30"}
//                                        ,{"356","20000","60","30"}};
//                                for (int i=0;i<array.length;i++) {
//
//                                    SUserRedenvelope sUserRedenvelope = new SUserRedenvelope();
//                                    sUserRedenvelope.setTitle("实名认证红包");
//                                    sUserRedenvelope.setContent("实名认证红包");
//                                    sUserRedenvelope.setUserId(Integer.parseInt(userId));
//                                    sUserRedenvelope.setAmount(new BigDecimal(array[i][0]));
//                                    sUserRedenvelope.setCreateTime(new Date());
//                                    sUserRedenvelope.setMinInvest(new BigDecimal(array[i][1]));
//                                    sUserRedenvelope.setMinDue(Integer.parseInt(array[i][2]));
//                                    sUserRedenvelope.setExpireTime(DateUtil.addDateDay(new Date(), Integer.parseInt(array[i][3])));
//                                    sUserRedenvelope.setStatus(0);
//                                    sUserRedenvelopeMapper.insertSelective(sUserRedenvelope);
//                                }

                                return ObjectResult.build("1", "绑卡成功");
                            } catch (Exception e) {
                                ExceptionUtils.recordException(true,"用户:"+user.getMobile()+"绑卡,保存成功记录操作数据库,发生异常", "", e);
                                return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                            }
                        }else {
                            return ObjectResult.build("0", "信息错误");
                        }

                    }else {
                        return ObjectResult.build("0", dataMap_1.get("message").toString());
                    }

                }else {
                    return objectResult;
                }
            }else {
                return ObjectResult.build("0", "银行卡信息错误");
            }

        }else {
            return result;
        }
    }

    @Override
    public Integer selectUserBankCoutByUserid(Long userId) {
        return userBankMapper.selectUserBankCoutByUserid(userId);
    }
}


